package com.sukumar.android.sms.receiver;

import com.sukumar.android.sms.R;
import com.sukumar.android.sms.activity.SMSPauseActivity;
import com.sukumar.android.sms.service.SmsNotifierService;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class SMSReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		Bundle bundle = intent.getExtras();
		Object messages[] = (Object[]) bundle.get("pdus");
		SmsMessage smsMessage[] = new SmsMessage[messages.length];
		SmsMessage smsMsg = null;

		for (int n = 0; n < messages.length; n++) {
			smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
		}

		for (int i = 0; i < smsMessage.length; i++) {
			smsMsg = smsMessage[i];

			if (smsMsg.getMessageBody().contains("BING")) {
				startService(context);
				sendNotification(context, smsMsg.getMessageBody());
			}
		}

	}

	private void sendNotification(Context pContext, String pNotification) {
		NotificationManager notificationManager = (NotificationManager) pContext
				.getSystemService(Context.NOTIFICATION_SERVICE);
		
		Notification notification = new Notification(R.drawable.icon,
				pContext.getText(R.string.bing_ticker), System.currentTimeMillis());

		notification.defaults |= Notification.DEFAULT_LIGHTS;
		notification.defaults |= Notification.DEFAULT_VIBRATE;
		notification.flags |= Notification.FLAG_SHOW_LIGHTS;
		notification.flags |= Notification.FLAG_INSISTENT;
		notification.flags |= Notification.FLAG_AUTO_CANCEL;


		Intent notificationIntent = new Intent(pContext, SMSPauseActivity.class);
		

		PendingIntent contentIntent = PendingIntent.getActivity(pContext, 0,
				notificationIntent, 0);
		notification.setLatestEventInfo(pContext, pContext.getText(R.string.bing_text), pNotification,
				contentIntent);
		notificationManager.notify(1234, notification);

	}


	private void startService(Context pContext) {
		@SuppressWarnings("static-access")
		ActivityManager manager = (ActivityManager) pContext
				.getSystemService(pContext.ACTIVITY_SERVICE);
		boolean running = false;
		for (RunningServiceInfo service : manager
				.getRunningServices(Integer.MAX_VALUE)) {
			if ("com.sukumar.android.sms.SmsNotifierService"
					.equals(service.service.getClassName())) {
				running = true;
			}

		}
		if(!running){
			pContext.startService(new Intent(pContext,
					SmsNotifierService.class));	
		}else{
			Toast toast = Toast.makeText(pContext,
					"Notificaition service already started",
					Toast.LENGTH_LONG);
			toast.show();
		}
		

	}
}
